/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package stendcontrol;

import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import services.ConvIntByte;

/**
 *
 * @author Asko
 */
public class DBInputStream extends InputStream {

    private final String READ_SQL = "select experiment,OCTET_LENGTH(experiment)"
            + " from exp_data where exp_id = ? and indexNumber = ?";
    private final String SELECT_COUNT = "select count(*)  "
            + "from exp_data where exp_id = ?";
    private int counter = 0;
    private static final int PACKET_LENGTH = 1024 * 500;
    private byte[] buf = new byte[PACKET_LENGTH];
    private Connection con;
    private int exp_id;
    private int index_num = 1;
    private int lines_cnt = 0;
    private long iterator = 0;
    private long bytesCnt = 0;

    public DBInputStream(Connection con, int exp_id) throws SQLException {
        this.con = con;
        this.exp_id = exp_id;
        PreparedStatement ps = con.prepareStatement(SELECT_COUNT);
        ps.setInt(1, exp_id);
        ResultSet set = ps.executeQuery();
        set.next();
        lines_cnt = set.getInt(1);
    }

    @Override
    public int read() throws IOException {
        if (counter == PACKET_LENGTH) {
            counter = 0;
        }
        try {
            if (counter == 0 && index_num < lines_cnt + 1) {
                PreparedStatement pstmt = con.prepareStatement(READ_SQL);
                pstmt.setInt(1, exp_id);
                pstmt.setInt(2, index_num++);
                ResultSet rs = pstmt.executeQuery();
                rs.next();
                byte[] bf = rs.getBytes(1);
                int cnt = rs.getInt(2);
                bytesCnt += cnt;
                System.arraycopy(bf, 0, buf, 0, bf.length);
                rs.close();
                pstmt.close();
            }

        } catch (SQLException ex) {
            ex.printStackTrace();
        }
        return (iterator++ < bytesCnt) ? ConvIntByte.byte2Int(buf[counter++]) : -1;
    }

    @Override
    public void close() throws IOException {
        super.close();
    }
}
